package me.ahy231.auth.filter;

import lombok.extern.slf4j.Slf4j;
import me.ahy231.auth.utils.JwtUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author ahy231
 * @date 2021/6/28 11:08
 * @description
 */
@Slf4j
public class TokenFilter extends BasicHttpAuthenticationFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            return executeLogin(request, response);
        } catch (Exception e) {
            request.setAttribute("err", e.getMessage());
            return false;
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        String token = getAuthzHeader(request);
        if (StringUtils.hasText(token)) {
            throw new RuntimeException("token为空");
        }

        Long openId = jwtUtils.getOpenIdFromToken(token);
        getSubject(request, response).login(new UsernamePasswordToken(Long.toString(openId), ""));
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        log.info("------------认证失败-------------");
        String err = (String) request.getAttribute("err");
        log.info("错误信息：{}", err);
        return false;
    }
}
